/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 广告控量
 */
import React, { useMemo, useRef, useCallback, useState } from 'react';
import { Popconfirm, Button, message, Space } from 'antd';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import { useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import { debounce } from 'lodash';
import { getControlAdvList, onlineOrDelete } from '@/services/operatorManagement';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import AdvControlEdit from './AdvControlEdit';
import type { AdvTableControlListItem } from '../types/Advertisements';

const AdvRelease: React.FC = () => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const [record, setRecord] = useState<AdvTableControlListItem>({} as any);
  const [editType, setEditType] = useState<'add' | 'edit'>('add');
  const [editVisible, setEditVisible] = useState<boolean>(false);
  const [onLineLoading, setOnLineLoading] = useState<boolean>(false);
  const [loadingID, setLoadingID] = useState<string>('');
  const formRef = useRef<ActionType>();

  const deleteAdvs = useCallback((plan_id: string) => {
    onlineOrDelete({ plan_id, plan_status: '3' }).then((res) => {
      if (res.code == 0) {
        formRef.current?.reload();
      } else {
        message.error(res.msg);
      }
    });
  }, []);

  const goOnline = useCallback(
    debounce(
      (plan_id: string, plan_status: string) => {
        setOnLineLoading(true);
        setLoadingID(plan_id);
        onlineOrDelete({ plan_id, plan_status }).then((res) => {
          setOnLineLoading(false);
          setLoadingID('');
          if (res.code == 0) {
            formRef.current?.reload();
          } else {
            message.error(res.msg);
          }
        });
      },
      300,
      {
        trailing: false,
        leading: true,
      },
    ),
    [],
  );

  const onAddClick = useCallback(() => {
    setEditVisible(true);
    setEditType('add');
  }, []);

  const onEditClick = useCallback((records: AdvTableControlListItem) => {
    setRecord(records);
    setEditType('edit');
    setEditVisible(true);
  }, []);

  const columns: ProColumns<AdvTableControlListItem>[] = useMemo(
    () => [
      {
        title: '序号',
        width: 80,
        dataIndex: 'plan_id',
        align: 'center',
        search: false,
      },
      {
        title: '控量名称',
        width: 100,
        dataIndex: 'plan_name',
        align: 'center',
        search: false,
      },
      {
        title: '控量广告位ID',
        width: 100,
        dataIndex: 'ad_id',
        align: 'center',
        search: false,
      },
      {
        title: '控量数量',
        width: 100,
        dataIndex: 'plan_count',
        align: 'center',
        search: false,
      },
      {
        title: '是否每日控量',
        width: 100,
        dataIndex: 'is_daily',
        align: 'center',
        search: false,
        render: (is_daily) => (is_daily === '1' ? '是' : '否'),
      },
      {
        title: '控量时间',
        width: 300,
        dataIndex: 'brand',
        align: 'center',
        search: false,
        render: (_, item: any) => `${item.plan_begin_date}-${item.plan_end_date}`,
      },
      {
        title: '创建时间',
        width: 150,
        dataIndex: 'created_at',
        align: 'center',
        search: false,
      },
      {
        title: '创建人',
        width: 150,
        dataIndex: 'creator',
        align: 'center',
      },
      {
        title: '操作',
        width: winSize === 'xs' ? 100 : 180,
        align: 'center',
        search: false,
        fixed: 'right',
        render: (_, item) => {
          const { plan_status, plan_id } = item;
          return (
            <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
              <Button
                key='0'
                type='primary'
                onClick={() => goOnline(plan_id, plan_status == '1' ? '2' : '1')}
                loading={loadingID === plan_id && onLineLoading}
                size='small'
              >
                {plan_status == '2' ? '上线' : '下线'}
              </Button>
              <Button
                key='1'
                type='primary'
                onClick={() => onEditClick(item)}
                disabled={plan_status == '1'}
                size='small'
              >
                编辑
              </Button>
              <Popconfirm
                key='2'
                title='确定删除该条广告？'
                onConfirm={() => deleteAdvs(plan_id)}
                disabled={plan_status == '1'}
              >
                <Button type='primary' danger disabled={plan_status == '1'} size='small'>
                  删除
                </Button>
              </Popconfirm>
            </Space>
          );
        },
      },
    ],
    [onLineLoading, loadingID, deleteAdvs, goOnline, onEditClick, winSize],
  );

  const getTableList = useCallback((params) => {
    const { current: page, pageSize, ...rest } = params;
    return getControlAdvList({ page, pageSize, ...rest });
  }, []);

  const onClose = useCallback(() => {
    setEditVisible(false);
    setRecord({} as any);
  }, []);

  return (
    <>
      <DragTable>
        <ProTable<AdvTableControlListItem>
          className='kb-pro-table'
          actionRef={formRef}
          rowKey={(rowKey) => rowKey.id}
          columns={columns}
          options={false}
          request={getTableList}
          search={{
            className: 'kb-pro-table-form',
            labelWidth: 'auto',
            collapseRender: () => false,
            optionRender: (searchConfig, formProps, dom) => [
              ...dom.reverse(),
              <Button key='add' onClick={onAddClick} type='primary'>
                生成控量
              </Button>,
            ],
          }}
          pagination={{
            pageSize: 20,
            showSizeChanger: false,
          }}
          scroll={{ x: 1300 }}
        />
      </DragTable>
      <AdvControlEdit
        type={editType}
        visible={editVisible}
        record={record}
        onClose={onClose}
        getList={() => formRef.current?.reload()}
      />
    </>
  );
};

export default AdvRelease;
